package com.ssyc.student.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.student.R;
import com.ssyc.student.activity.StudentChooseQuestionTypeActivity;
import com.ssyc.student.activity.StudentPrepareDetectionActivity;
import com.ssyc.student.activity.StudentShowPrepareDetectionAnswerActivity;
import com.ssyc.student.adapter.StGvPrepareDetectionShowAnswerAdapter;
import com.ssyc.student.bean.ChooseAnswerInfo;
import com.ssyc.student.bean.CommitInfo;
import com.ssyc.student.bean.PrepareDetectionInfo;
import com.ssyc.student.bean.ResultHourInfo;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--预习检测--提交界面
 * Created by Administrator on 2018/5/10 0010.
 */

public class StudentPrepareDetectionCommitFragment extends LazyBaseFragment implements View.OnClickListener {
    //字母数组
    private String[] chartNums;
    //务器返回的正确答案的数组
    private String[] right_answers;
    //服务器返回的提供选择的答案选项
    private List<String> choose_answers;

    public static StudentPrepareDetectionCommitFragment newInstance(PrepareDetectionInfo.DataBean.QuestionListBean question, String lessonId, String gradeId) {

        StudentPrepareDetectionCommitFragment studentPrepareDetectionCommitFragment = new StudentPrepareDetectionCommitFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(CHOOSEANSWER, question);
        studentPrepareDetectionCommitFragment.setArguments(bundle);
        bundle.putString(LESSONID, lessonId);
        bundle.putString(GRADEID, gradeId);

        return studentPrepareDetectionCommitFragment;
    }

    //question对象的Key
    public static final String CHOOSEANSWER = "StudentPrepareDetectionCommitFragment.class";

    //用户开始做题对应的key
    public static final String FIRSTTIME = "firsttime";

    //课程Lesson对应的Id
    public static final String LESSONID = "lessonId";

    //课程对应的GradeId
    public static final String GRADEID = "gradeId";

    //精力
    public static final String ENERGY = "energy";


    //当前的Question对象
    public PrepareDetectionInfo.DataBean.QuestionListBean question;

    //当前Question对象对应的LessonId
    public String lessonId;

    //当前Question对象对应的GradeId
    public String gradeId;


    //题目是否完成的提示语
    //1、用户完成了所有的题提示语为：完成啦，提交吧
    //2、用户还有题未做完提示语未
    private TextView tvStateMsg;

    //展示所有题目状态的列表
    private MyGridView gv;

    //展示答题的列表的数据集合
    private List<ChooseAnswerInfo> chooseAnswerInfos;

    //提交按钮
    private Button btCommit;

    //列表适配器
    private StGvPrepareDetectionShowAnswerAdapter adapter;

    //Activity中用于保存用户答题状态的集合
    private Map<Integer, String> chooseAnswerMap;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_prepare_detection_commit;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }


    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);

        showContent();

        //初始化视图
        initView(view);

        //获取页面数据
        initData();

        //设置提示文字信息需要显示的文字
        setMsg();

        //设置展示列表
        initRv();
    }

    /**
     * 初始化View
     *
     * @param view
     */
    public void initView(View view) {
        tvStateMsg = view.findViewById(R.id.tv_state_msg);
        gv = view.findViewById(R.id.gv);
        btCommit = view.findViewById(R.id.bt_commit);
        btCommit.setOnClickListener(this);
    }


    /**
     * 获取页面数据
     */
    private void initData() {
        //获取传递过来的Question对象
        question = (PrepareDetectionInfo.DataBean.QuestionListBean) getArguments().getSerializable(CHOOSEANSWER);

        //当前Question对象对应的LessonId
        lessonId = getArguments().getString(LESSONID);

        //当前Question对象对应的GradeId
        gradeId = getArguments().getString(GRADEID);


        //获取A到Z的字母数组
        chartNums = getResources().getStringArray(R.array.base_letters);

        //服务器返回的正确答案的字符串切割厚道 数组
        right_answers = question.getWordpic().split("￠");

        //服务器提供的供选择的答案选项
        choose_answers = new ArrayList<>();

        List<PrepareDetectionInfo.DataBean.QuestionListBean.JpglistBean> jpglist = question.getJpglist();
        if (null != jpglist && jpglist.size() != 0) {
            for (int i = 0; i < jpglist.size(); i++) {
                //去除空格
                choose_answers.add(jpglist.get(i).getText());
            }
        }

        //获取Activity中保存的选择答案的map对象
        chooseAnswerMap = StudentPrepareDetectionActivity.getUnderLineMap();

        //初始化页面展示选择答案的集合
        chooseAnswerInfos = new ArrayList<>();

        //遍历Map取出需要展示的选择题的答案
        for (int i = 0; i < chooseAnswerMap.size(); i++) {
            ChooseAnswerInfo info = new ChooseAnswerInfo();
            //生出展示的序号12345...
            info.setAnswerIndex(i + 1);
            //用户选择的答案的字母序列,判断的方法,根据Activity中Map当前条目保存的Value来判断,如果当前
            //Value为""或者5个下划线则证明用户没有填空当前位置或者清空了当前位置的选项,都认为用户还没作答完毕
            //对info的当前位置的字母序列赋值为""
            //否则取出Map当前条目的的Value值取出前后空格后赋值给info的字母序列
            if (TextUtils.isEmpty(chooseAnswerMap.get(i)) || StudentPrepareDetectionActivity.regStr.equals(chooseAnswerMap.get(i))) {
                //证明没作答或者取消了作答
                info.setAnswerFlag("");
            } else {
                //已经作答过
                info.setAnswerFlag(chooseAnswerMap.get(i).trim());
            }
            //加入集合
            chooseAnswerInfos.add(info);
        }
    }


    /**
     * 设置提示信息需要显示的文字
     */
    private void setMsg() {
        if (hasChooseAnswer()) {
            tvStateMsg.setText("完成啦,提交吧!");
        } else {
            tvStateMsg.setText("请完成题目后在提交");
        }
    }


    /**
     * 设置展示列表数据
     */
    private void initRv() {
        adapter = new StGvPrepareDetectionShowAnswerAdapter(getContext(), chooseAnswerInfos, R.layout.student_gv_show_answer);
        gv.setAdapter(adapter);
    }


    /**
     * 判断是否全部答题的方法
     *
     * @return
     */
    public boolean hasChooseAnswer() {
        boolean res = true;
        for (int i = 0; i < chooseAnswerInfos.size(); i++) {
            if (TextUtils.isEmpty(chooseAnswerInfos.get(i).answerFlag)) {
                res = false;
                break;
            }
        }

        return res;
    }

    /**
     * 处理重新做题后的事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.getType() == StudentPrepareDetectionActivity.REFORMTYPE) {
            //用户选择了答案或者用户取消了已经选择答案后的事件
            for (int i = 0; i < chooseAnswerMap.size(); i++) {

                //用户选择的答案的字母序列,判断的方法,根据Activity中Map当前条目保存的Value来判断,如果当前
                //Value为""或者5个下划线则证明用户没有填空当前位置或者清空了当前位置的选项,都认为用户还没作答完毕
                //对info的当前位置的字母序列赋值为""
                //否则取出Map当前条目的的Value值取出前后空格后赋值给info的字母序列
                if (TextUtils.isEmpty(chooseAnswerMap.get(i)) || StudentPrepareDetectionActivity.regStr.equals(chooseAnswerMap.get(i))) {
                    //证明没作答或者取消了作答
                    chooseAnswerInfos.get(i).setAnswerFlag("");
                } else {
                    //已经作答过
                    chooseAnswerInfos.get(i).setAnswerFlag(chooseAnswerMap.get(i).trim());
                }
            }
            adapter.notifyDataSetChanged();

            //设置提示语
            setMsg();
        }
    }

    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.bt_commit) {
            //提交
            if (hasChooseAnswer()) {

                //上传服务器
                httpCommit();

            } else {
                UiUtils.Toast("请完成题目后在提交", false);
                return;
            }
        }
    }


    /**
     * 做完题目后上传服务器的操作方法
     */
    private void httpCommit() {

        CommitInfo commitInfo = new CommitInfo();

        //级别
        commitInfo.setGrade_id(gradeId);

        //课程编号
        commitInfo.setLesson_id(lessonId);

        //模块编号
        commitInfo.setModule_id("12");

        //题目总数量
        commitInfo.setAmount(chooseAnswerInfos.size() + "");

        //正确题目数量
        commitInfo.setAmount_t(getChooseRightCount() + "");

        //总分
        commitInfo.setScore("0");

        //得分
        commitInfo.setScore_t("0");

        //获取上传时间
        long useTime = TimeCount.newInstance().getTotalTime() + (System.currentTimeMillis() - TimeCount.newInstance().getLastTime());

        //转化为秒
        String seconds = useTime / 1000 + "";

        commitInfo.setSeconds(seconds);

        List<CommitInfo.SubjectBean> subjectBeans = new ArrayList<>();

        for (int i = 0; i < chooseAnswerInfos.size(); i++) {
            CommitInfo.SubjectBean subjectBean = new CommitInfo.SubjectBean();

            //题目编号
            subjectBean.setQuestion_id(question.getTitle() + "");

            //题型编号
            subjectBean.setType_id(question.getTitletype() + "");

            //正确与否
            String flag = chooseAnswerInfos.get(i).getAnswerFlag();//获取到选择ABCDE

            //获取该项选择的内容
            String content = choose_answers.get(getIndex(flag));

            //填空内容
            subjectBean.setContent(content);

            //获取填空的该位置的正确和错误
            if (content.replaceAll(" ", "").equals(right_answers[i].replaceAll(" ", ""))) {
                //正确
                subjectBean.setResult("1");
            } else {
                //错误
                subjectBean.setResult("0");
            }

            //得分
            subjectBean.setScore("0");

            subjectBeans.add(subjectBean);
        }

        commitInfo.setSubject(subjectBeans);


        //转换成JSON字符串
        String postServerJson = GsonUtil.objectToJson(commitInfo);

        Log.i("test", "上传给服务器的JSON是:" + postServerJson);

        CustomDialogManager.show(getContext(), "上传中...");

        Map<String, String> map = new HashMap<>();
        map.put("type", "24");
        map.put("acc", AccountUtils.getAccount(getContext()));
        map.put("role", AccountUtils.getRole(getContext()));
        map.put("studys", postServerJson);
        map.put("apptoken", AccountUtils.getToken(getContext()));
        map.put("platform", "8");
        if (TextUtils.isEmpty(RecordTimeUtil.energy)) {
            map.put("energy", "0");
        } else {
            map.put("energy", RecordTimeUtil.energy);
        }
        HttpUtils.post(HttpAdress.COMMITSCORE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                ResultHourInfo info = null;
                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, ResultHourInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                    if (info != null) {
                        if ("200".equals(info.state)) {
                            //发送已经做完的更新
                            BusInfo stateInfo = new BusInfo();
                            stateInfo.setType(StudentChooseQuestionTypeActivity.UPDATAPAGESTATE);
                            EventBus.getDefault().post(stateInfo);
                            //上传成功
                            if(!TextUtils.isEmpty(info.name)){
                                UiUtils.Toast("恭喜获得新成就"+info.name, false);
                            }
                            //跳转到展示阅读答题结果的界面同时需要通过将Activity的计时时间携带给下个界面
                            goToShowAnswerActivity();
                        } else {
                            UiUtils.Toast("提交失败,错误码是:" + info.state, false);
                            Log.i("test", "错误码是:" + info.state);
                        }
                    }
                }
            }
        });

    }

    /**
     * 获取选择正确答案的方法
     *
     * @return
     */
    private int getChooseRightCount() {
        int conunt = 0;
        for (int k = 0; k < chooseAnswerInfos.size(); k++) {
            //当前位置选择的答案
            String content = choose_answers.get(getIndex(chooseAnswerInfos.get(k).answerFlag));

            if (content.replaceAll(" ", "").equals(right_answers[k].replaceAll(" ", ""))) {
                //正确
                conunt++;
            }
        }
        return conunt;
    }

    /**
     * 跳转到阅读答案展示界面的Acitivity
     */
    private void goToShowAnswerActivity() {

        for (int i = 0; i < chooseAnswerInfos.size(); i++) {
            if (chooseAnswerInfos.get(i).answerFlag.equals(getRightNum(i, right_answers, choose_answers, chartNums))) {
                //选择的答案正确
                chooseAnswerInfos.get(i).isCorrect = true;
            } else {
                //选择的答案错误
                chooseAnswerInfos.get(i).isCorrect = false;
            }
        }

        Intent intent = new Intent(getContext(), StudentShowPrepareDetectionAnswerActivity.class);

        //携带用户作答的集合过去
        intent.putExtra(StudentShowPrepareDetectionAnswerActivity.SHOWANSWER, GsonUtil.listToJson(chooseAnswerInfos));

        //将用户开始做题的时间传递过去
        intent.putExtra(FIRSTTIME, StudentPrepareDetectionActivity.getFirstTime());

        startActivity(intent);
    }


    /**
     * 根据服务器返回的每一项的正确答案来确定正确答案在服务器返回的选择答案选项中的位置，根据位置来确定索引ABCDEFGH
     *
     * @param pos
     */
    private String getRightNum(int pos, String[] rightAnswers, List<String> choose_answers, String[] chartNums) {
        int index = -1;
        for (int i = 0; i < choose_answers.size(); i++) {

            if (rightAnswers[pos].replaceAll(" ", "").equals(choose_answers.get(i).replace(" ", ""))) {
                index = i;
                break;
            }
        }

        //根绝返回的位置来确定正确答案的索引
        return chartNums[index];
    }


    /**
     * 根据选择的ABCDEF来获取选择的答案在服务器返回的提供选择答案项目的位置
     */

    private int getIndex(String flag) {
        int index = -1;
        for (int j = 0; j < chartNums.length; j++) {
            if (flag.equals(chartNums[j])) {
                index = j;
                break;
            }
        }

        return index;
    }

}
